﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using MebAppMarketplace.Biz;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace MebAppMarketplace.Controllers
{
    /// <summary>
    /// 后台功能，用户模块，用于管理用户注册申请，帮助用户重置密码等
    /// </summary>
    [Authorize]
    public class UserManagementController : Controller
    {
        public UserService userService { get; set; }
        public IActionResult RegisterList(int page)
        {
            var list = userService.GetRegisterList(page);
            return View(list);
        }

        public IActionResult Reject(Guid id)
        {
            if (userService.IsRegistrationAudited(id))
            {
                ModelState.AddModelError("", "已审核，不可重复审核");
            }
            if (!ModelState.IsValid)
                this.ViewDataErrorFromModelState("Error");
            return View();
        }
        [HttpPost]
        public IActionResult Reject(Guid id, string message)
        {
            if (userService.IsRegistrationAudited(id))
            {
                ModelState.AddModelError("", "已审核，不可重复审核");
            }
            if (ModelState.IsValid)
            {
                userService.RejectRegistration(id, message);
                return Redirect(Request.Query["returnUrl"]);
            }
            else
            {
                this.ViewDataErrorFromModelState("Error");
                return View();
            }
        }

        public IActionResult SetPassword()
        {
            return View();
        }

        [HttpPost]
        public IActionResult SetPassword(Guid id, string password)
        {
            var m = userService.DbSet.Find(id);
            if (m == null)
            {
                return this.NotFound();
            }
            if (string.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("password", "请填写密码");
            }
            if (ModelState.IsValid)
            {
                userService.SetPassword(id, password);
                return Redirect(Request.Query["returnUrl"]);
            }
            return this.ViewError();
        }
        public IActionResult SetRole()
        {
            return View();
        }

        [HttpPost]
        public IActionResult SetRole(Guid id, string role)
        {
            var m = userService.DbSet.Find(id);
            if (m == null)
            {
                return this.NotFound();
            }
            if (ModelState.IsValid)
            {
                userService.SetRole(id, role);
                return Redirect(Request.Query["returnUrl"]);
            }
            return this.ViewError();
        }
    }
}
